﻿using System.Collections;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Fluffy.Library.Mvvm;
using System;
using System.IO;
using System.Linq;
using Fluffy.Library.Utils;
using Microsoft.Win32;

namespace Fluffy.FileMenuCommands
{
	internal class OpenCommandViewModel : ViewModelBase
	{
		private readonly OpenCommandModel _model;

		internal OpenCommandViewModel(OpenCommandModel model)
		{
			if (model == null) 
				throw new ArgumentNullException("model");

			_model = model;
			_model.RecentDocumentsListChanged += () => OnPropertyChanged("RecentDocuments");
		}

		public IList RecentDocuments
		{
			get { return _model.RecentDocuments.Where(File.Exists).Select(x => new FilePathViewModel(x)).ToArray(); }
		}

		public ICommand OpenDocumentCommand
		{
			get { return new Command(OnOpenDocument); }
		}

		public ICommand OpenSpecifiedDocumentCommand
		{
			get { return new Command<string>(OnOpenSpecifiedDocument); }
		}

		private void OnOpenDocument()
		{
			OpenFileDialog dialog = new OpenFileDialog { CheckFileExists = true };
			bool? result = dialog.ShowDialog(Application.Current.MainWindow);

			if (result.HasValue && result.Value)
			{
				OnOpenSpecifiedDocument(dialog.FileName);
			}
		}

		private void OnOpenSpecifiedDocument(string path)
		{
			_model.OpenFile(path);
		}
	}

	internal class FilePathViewModel : ViewModelBase
	{
		private readonly string _path;

		public FilePathViewModel(string path)
		{
			_path = path;
		}

		public string FileName
		{
			get { return Path.GetFileName(_path); }
		}

		public string FileDir
		{
			get { return Path.GetDirectoryName(_path); }
		}

		public string FilePath
		{
			get { return _path; }
		}

		public ImageSource Icon
		{
			get { return UiUtils.GetFileIcon(_path, true); }
		}
	}
}
